# 渠道管理
class Api::RegionsController < Api::BaseController
	skip_before_filter :valid_permission
	before_filter :valid_cadmin

	# 渠道列表
	# 
	# Params
	# 	access_token: [String] authenication_token
	#   page: [Integer] 页码
	#   per: [Integer] 每页显示数
	# Return
	# 	status: [String] success
	#   list: [Hash] {{id, name, user_name, user_mobile}...}
	#   total: [Integer] 总数
	# Error
	#   status: [String] failed
	def index
		regions = @account.regions.page(params[:page]).per(params[:per])
		render json: {status: :success, list: regions.map(&:to_hash), total: regions.total_count}
	end

  def show
    region = @account.regions.find_by(id: params[:id])
    render json: {msg: "无效的渠道", status: :failed} and return unless region
    stores = region.stores.page(params[:page])
    render json: {status: :success, stores: stores.map(&:to_hash), total: stores.total_count}
  end

	# 添加新渠道
	# 
	# Params
	# 	access_token: [String] authenication_token
	# 	region_name: [String] 渠道名称
	# 	admin[name]: [String] 渠道负责人名称
	# 	admin[mobile]: [String] 渠道负责人手机号
	#
	# Return
	# 	status: [String] success
	# 	msg: [String] 创健成功
	# Error
	#   status: [String] failed
	#   msg: [String] msg_infos
	def create
		raise '渠道名称重复，无法添加' if @account.regions.where(name: params[:region_name]).count > 0
		
		radmin = User.find_or_initialize_by(mobile: params[:admin][:mobile])

		raise '用户已经注册，请重新创建' unless radmin.new_record? 
		
		User.transaction do
			Region.transaction do
				radmin.name 		= params[:admin][:name]
				radmin.password = ENV['init_ps']
				radmin.account 	= @current_user.account
				radmin.role 		= 'operator_director'
				radmin.save!

				@account.regions.create!(name: params[:region_name], user_id: radmin.id)

				render json: {status: :success, mesg: '创健成功'}
			end
		end

		rescue => e
			render json: {status: :failed, msg: e.message}
	end

	private

	def valid_cadmin
		if @current_user.role == 'admin' && @account.class == Company
		else
			raise '您无权访问' 
		end

		rescue => e
			render json: {status: :failed, msg: e.message}
	end

end
